//
//  WPVideoAndVoiceCell.m
//  wobingwoyi
//
//  Created by WGP on 2016/11/15.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPVideoAndVoiceCell.h"
#import "TZAssetModel.h"
#import <AVFoundation/AVFoundation.h>
#import "TZImageManager.h"
#import "SDTransparentPieProgressView.h"
#import <MediaPlayer/MediaPlayer.h>

#define iOS8Later ([UIDevice currentDevice].systemVersion.floatValue >= 8.0f)
@interface WPVideoAndVoiceCell ()

@property(nonatomic,strong)UIImageView *bgImageView;
@property(nonatomic,strong)UILabel *timeLabel;
@property(nonatomic,strong)UIImageView *iconImageView;
@property (nonatomic, copy) NSString *representedAssetIdentifier;
@property (nonatomic, assign) PHImageRequestID imageRequestID;

@end
@implementation WPVideoAndVoiceCell

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self setupUI];
    }
    return self;
}

-(void)setupUI
{
    [self bgImageView];
    [self timeLabel];
    [self iconImageView];
    
//    [self progressView];
    [self failedImageView];
}

-(UIImageView *)bgImageView
{
    if (_bgImageView == nil)
    {
        _bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"audio_bg"]];
        _bgImageView.contentMode = UIViewContentModeScaleAspectFill;
        _bgImageView.clipsToBounds = YES;
        [self.contentView addSubview:_bgImageView];
        
        [_bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.contentView);
        }];
    }
    return _bgImageView;
}

-(UIImageView *)iconImageView
{
    if (_iconImageView == nil)
    {
        _iconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zw_audio_icon"]];
        [self.contentView addSubview:_iconImageView];
        
        [_iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contentView).offset(5);
            make.bottom.equalTo(self.contentView).offset(-16);
        }];
    }
    return _iconImageView;
}

-(UILabel *)timeLabel
{
    if (_timeLabel == nil)
    {
        _timeLabel = [UILabel new];
        _timeLabel.textAlignment  =NSTextAlignmentRight;
        _timeLabel.text = @"00:04";
        _timeLabel.font = [UIFont systemFontOfSize:12];
        _timeLabel.textColor = RGB_SAME(153);
        [self.contentView addSubview:_timeLabel];
        
        [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.iconImageView);
            make.right.equalTo(self.contentView).offset(-10);
        }];
    }
    return _timeLabel;
}

-(SDTransparentPieProgressView *)progressView
{
    if (_progressView == nil)
    {
        CGFloat itemWidth = (SCREEN_WIDTH - 40)/3.0;
        _progressView = [[SDTransparentPieProgressView alloc] init];
        _progressView.layer.cornerRadius = itemWidth*0.5*0.5;
        _progressView.layer.masksToBounds = YES;
        _progressView.progress = 0.0;
        [self.contentView addSubview:_progressView];
        
        [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.contentView);
            make.width.height.mas_equalTo(itemWidth*0.5);
        }];
    }
    return _progressView;
}

-(UIImageView *)failedImageView
{
    if (_failedImageView == nil)
    {
        _failedImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"videoOrAudioUploadFailed"]];
        _failedImageView.hidden = YES;
        [self.contentView addSubview:_failedImageView];
        
        [_failedImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.contentView);
        }];
    }
    return _failedImageView;
}

-(void)setModel:(TZAssetModel *)model
{
    _model = model;
    
    if (model.type == TZAssetModelMediaTypeAudio)
    {
        self.bgImageView.image = [UIImage imageNamed:@"audio_bg"];
        self.iconImageView.image = [UIImage imageNamed:@"zw_audio_icon"];
        
        NSError *error;
        
        if ([model.urlPath.absoluteString hasPrefix:@"file://"])
        {
            AVAudioPlayer *audioPlayer =  [[AVAudioPlayer alloc] initWithContentsOfURL:model.urlPath error:&error];
            float duration = (float)audioPlayer.duration;
            NSString *timeStr = [NSString timeStrWithDurations:duration];
            model.timeLength = timeStr;
            self.timeLabel.text = timeStr;
        }
        else
        {
            self.timeLabel.text = model.timeLength;
        }
        
    }
    else
    {
        if(model.asset)
        {
            if (iOS8Later) {
                self.representedAssetIdentifier = [[TZImageManager manager] getAssetIdentifier:model.asset];
            }
            PHImageRequestID imageRequestID = [[TZImageManager manager] getPhotoWithAsset:model.asset photoWidth:self.self.frame.size.width completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
                // Set the cell's thumbnail image if it's still showing the same asset.
                if (!iOS8Later)
                {
                    self.bgImageView.image = photo;
                    return;
                }
                if ([self.representedAssetIdentifier isEqualToString:[[TZImageManager manager] getAssetIdentifier:model.asset]])
                {
                    self.bgImageView.image = photo;
                } else
                {
                    // NSLog(@"this cell is showing other asset");
                    [[PHImageManager defaultManager] cancelImageRequest:self.imageRequestID];
                }
                if (!isDegraded) {
                    self.imageRequestID = 0;
                }
            }];
            
            if (imageRequestID && self.imageRequestID && imageRequestID != self.imageRequestID) {
                [[PHImageManager defaultManager] cancelImageRequest:self.imageRequestID];
                
            }
            self.imageRequestID = imageRequestID;
        }
        else
        {
            if (model.imageURL.length)
            {
                [self.bgImageView sd_setImageWithURL:[NSURL URLWithString:model.imageURL] placeholderImage:[UIImage imageNamed:@"placeholder_Image"]];
            }
            else
            {
                UIImage *bgImage = [self getScreenShotImageFromVideoPath:model.urlPath.absoluteString];
                self.bgImageView.image = bgImage;
            }
        }
        
        self.timeLabel.text = model.timeLength;
        self.iconImageView.image = [UIImage imageNamed:@"zw_video_icon"];
    }
    
//    self.progressView.hidden = self.model.isUploaded;
}
/**
 *  获取视频的缩略图方法
 *
 *  @param filePath 视频的本地路径
 *
 *  @return 视频截图
 */
- (UIImage *)getScreenShotImageFromVideoPath:(NSString *)filePath{
    
    UIImage *shotImage;
    //视频路径URL
    NSURL *fileURL = [NSURL URLWithString:filePath];
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:fileURL options:nil];
    
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    gen.appliesPreferredTrackTransform = YES;
    
    CMTime time = CMTimeMakeWithSeconds(0.0, 100);
    
    NSError *error = nil;
    
    CMTime actualTime;
    
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    
    if (error)
    {
        NSLog(@"%@",error);
    }
    
    shotImage = [[UIImage alloc] initWithCGImage:image];
    
    CGImageRelease(image);
    
    return shotImage;
    
}

@end
